package com.zhiwang.planet.ui.jsmodule

import android.content.DialogInterface
import android.util.Log
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.planet.processor.JsModule
import com.zhiwang.planet.event.AppUsageEvent
import com.zhiwang.planet.service.AppUsageService
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.util.AppDetector
import com.zhiwang.planet.util.Toaster
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@JsModule
class AppUsageModule constructor(context: BaseActivity, val reload: () -> Unit) : BaseJsModule(context), LifecycleObserver {

    val TAG = "AppUsageModule"

    var appUsageTaskRunning = false
    var appUsageTaskId = ""
    var appTaskCompleted = false
    var retryCount = 0

    init {
        EventBus.getDefault().register(this)

        context.lifecycle.addObserver(this)
    }


    @OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
    fun onResume() {
        if (appUsageTaskId.isNotEmpty()) {
            reload()
            if (appTaskCompleted.not() && appUsageTaskRunning)
                Toaster.message("未完成任务，请继续试玩")
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAppUsageTaskComplete(event: AppUsageEvent) {
        if (this.appUsageTaskId == event.taskId) {
            Log.i(TAG, "onAppUsageTaskComplete: ")
            appTaskCompleted = true
        }
    }

    @JavascriptInterface
    fun startListenTargetAppUsage(taskId: String, pkgName: String, time: String) {
        this.appUsageTaskId = taskId
        context.runOnUiThread {
            if (AppDetector.hasAppUsagePermission(this).not()) {
                AppDetector.requestPermission(this)
            } else {
                AppUsageService.startDetectApp(this, taskId, pkgName, time.toInt())
                appUsageTaskRunning = true
            }
        }
    }

    @JavascriptInterface
    fun hasAppUsagePermission(): String {
        val allowed = AppDetector.hasAppUsagePermission(this)

        if (allowed.not()) {
            retryCount++
            AlertDialog.Builder(this)
                    .setTitle("温馨提示")
                    .setMessage("请先打开 App 使用情况权限后回到该页面领取任务")
                    .setNegativeButton("取消") { dialogInterface: DialogInterface, i: Int ->
                        dialogInterface.dismiss()
                    }.setPositiveButton("开启") { dialogInterface: DialogInterface, i: Int ->
                        AppDetector.requestPermission(this)
                    }
                    .create()
                    .show()
        }
        return allowed.toString()
    }


    @OnLifecycleEvent(value = Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        EventBus.getDefault().unregister(this)
    }

}